CLIENT_IP_PATH="/lich4/client_iplist"
_iscsi_vip=`cat /opt/fusionstack/etc/lich.conf|grep iscsi_vip|awk '{print $2 }'|awk -F/ '{ print $1 }'`

function update_ip()
{   	
	netstat -ant |grep ":3260"| awk -F ":" '{print $2}'|awk '{print $2}'|grep -v "0.0.0.0" |sort |uniq | {
		while read _dst; do
			if [ -n "$_dst" ]; then
				_mac=`arp -a -n |grep $_dst|awk '{ print $4 }'`

				if [ -n "$_mac" ]; then
					/usr/bin/etcdctl set /lich4/client_iplist/$_dst $_mac -ttl 120 > /dev/null
				fi
			fi
		done
	}

    #add local ip and mac

    local_ip=`hostname -i`
    
    if [ -n "$local_ip" ]; then
	    local_mac=`ifconfig -a 2>/dev/null |grep -A 4 $local_ip |grep -iE 'infiniband|ether' |awk '{print $2}'`
    fi

    if [ -n "$local_mac" ]; then
    	/usr/bin/etcdctl set /lich4/client_iplist/$local_ip $local_mac -ttl 120 > /dev/null
    fi
    
}

function ping_ip()
{
        if [ -z $_iscsi_vip ] ; then
                return 0
        fi

	_scsi_vip_mac=`ifconfig -a 2>/dev/null |grep -A 4 $_iscsi_vip |grep -iE 'infiniband|ether' |awk '{print $2}'`
        if [ -z $_scsi_vip_mac ] ; then
                return 0
        fi

	eth_x=`ip addr|grep $_iscsi_vip|awk '{ print $8}'|awk -F: '{ print $1}'`	
        if [ -z $eth_x ] ; then
                return 0
        fi

        etcdctl ls /lich4/client_iplist|{ while read _key; do
        	 	mac_remote=`etcdctl get $_key`
			if [ -z $mac_remote ] ; then
                		return 0
		        fi

        	 	ip_remote=`echo $_key|awk -F/ '{ print $4 }'`
			if [ -z $ip_remote ] ; then
                                return 0
                        fi

             #/opt/fusionstack/lich/libexec/lich_arp $eth_x $_iscsi_vip $_scsi_vip_mac $ip_remote $mac_remote 10
             net_disk=`ifconfig -a 2>/dev/null | grep -B 1 $_iscsi_vip | sed -n '1p' | awk -F':' '{print $1}'`
             if [[ $ip_remote != `hostname -i` ]];then
                 /usr/sbin/arping -c 2 -I $net_disk -s $_iscsi_vip $ip_remote
             fi
        done
        }
}

function arp_ping_client()
{
    etcdctl ls $CLIENT_IP_PATH >>  /dev/null
        ret=`echo $?`
        if [[ $ret != 0 ]];then
                etcdctl mkdir $CLIENT_IP_PATH
        fi

        while [ 1 ]
        do
           update_ip
           ping_ip
           sleep 1
        done

}

number=`ps -ef | grep 'check_client_ip' | grep -v 'grep'|wc -l`
if [[ $number -le 2 ]];then
    arp_ping_client
fi

